package demo1;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-02
 * Time: 14:59
 */
public class demo_volatile {
    //每次访问都会强制从主内存读取，每次修改都会立即写回主内存
    //去除volatile关键字会导致thread1线程在访问num时不从主内存读取
    public static volatile int num = 0;

    public static void main(String[] args) {
        //thread1线程的生命周期掌握在thread2手中
        Thread thread1 = new Thread(()->{
            while (num == 0){}
            System.out.println("Over thread1");
        });
        Thread thread2 = new Thread(()->{
            System.out.println("请输入一个整数");
            Scanner in = new Scanner(System.in);
            num = in.nextInt();
        });
        thread1.start();
        thread2.start();
    }
}
